/*
 * 字符串 相关操作
 *
 * @Author:    zhoujk
 * @Date:      2022-09-06 20:58:49
 */

/**
 * 转为 小写中划线
 */
export function convertLowerHyphen(str) {
  if (!str) {
    return ''
  }

  return str
    .replace(/([A-Z])/g, '-$1')
    .toLowerCase()
    .substring(1)
}
/**
 * 转为驼峰
 */
export function convertUpperCamel(str) {
  if (!str) {
    return ''
  }

  str = str.replace(/_(\w)/g, (_, letter) => letter.toUpperCase())
  // 首字母大写
  return str[0].toUpperCase() + str.substring(1)
}

/**
 * 转为驼峰
 */
export function convertLowerCamel(str) {
  if (!str) {
    return ''
  }

  return str.replace(/_(\w)/g, (_, letter) => letter.toUpperCase())
}

/**
 * 转为 小写下划线
 */
export function convertLowerUnderlineRecursion(obj) {
  if (obj === null || typeof obj !== 'object') return obj

  if (Array.isArray(obj)) {
    return obj.map((item) => convertLowerUnderlineRecursion(item))
  }

  return Object.keys(obj).reduce((acc, key) => {
    const newKey = key.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`)
    const value = obj[key]

    acc[newKey] = typeof value === 'object' ? convertLowerUnderlineRecursion(value) : value
    return acc
  }, {})
}

/**
 * 转为小驼峰
 */
export function convertLowerCamelRecursion(obj) {
  if (obj === null || typeof obj !== 'object') return obj

  if (Array.isArray(obj)) {
    return obj.map((item) => convertLowerCamelRecursion(item))
  }

  return Object.keys(obj).reduce((acc, key) => {
    const newKey = key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase())
    const value = obj[key]

    acc[newKey] = typeof value === 'object' ? convertLowerCamelRecursion(value) : value
    return acc
  }, {})
}
